App({
  globalData: {
    systemInfo: null,//客户端设备信息
    tabBar: {
      "list": [{
        "pagePath": "/pages/home/home",
        "text": "首页",
        "iconPath": "icon/No_firstPage.png",
        "selectedIconPath": "icon/firstPage.png"
      },
      {
        "pagePath": "/pages/project/project",
        "text": "项目",
        "iconPath": "icon/No_project.png",
        "selectedIconPath": "icon/project.png"
      },
      {
        "pagePath": "/pages/middle/middle",
        "iconPath": "icon/icon_release.png",
        "isSpecial": true,
        "text": "发布"
      },
      {
        "pagePath": "/pages/message/message",
        "text": "消息",
        "iconPath": "icon/No_message.png",
        "selectedIconPath": "icon/message.png"
      },
      {
        "pagePath": "/pages/me/me",
        "text": "我的",
        "iconPath": "icon/No_me.png",
        "selectedIconPath": "icon/me.png"
      }
    ]
    },
    allUser:{},
    userInfo: {},
    teamInfo:{},
    openid: "",

  },
  async getOpenid() {
    const db=wx.cloud.database()
    var that = this;
    var openidStor = wx.getStorageSync('openid')
    if (openidStor=="") {
      //调用云函数获取openid
      const res = await wx.cloud.callFunction({name: "getOpenid"});
      const openid = res.result.openid;
      that.globalData.openid = res.result.openid;
      wx.setStorageSync('openid', res.result.openid)
      console.log('获取了openid  1');
      //先查看是否该openid在all_user中已经存在，避免因为缓存清理而导致重复的用户数据
      const judge = await db.collection('all_user').where({ _openid : openid})
              .get()
              .then((res)=>{
                console.log(res)
                if(!res.data.length){
                  console.log('没有用户  2')
                  return true;
                }
                else{
                  console.log('已有用户  2',res.data[0])
                  return false;
                }
              });
      if(judge){
        await db.collection("all_user")
          .add({
            data: {
              userInfo: {},
              will_be_admit:[],
              has_be_reject:[],
              has_be_admit:[],
              point:[],
              prize:[],
              exe:[],
              mySession_ids:[],
              clockInTime:0
            }
          })
          .then(res => {
            console.log("添加新用户成功 3", res)
          })
      }else{
        console.log('无需添加用户数据于all_user');
        return;
      }
    }
    else {
      console.log("已经进去过小程序")
      console.log("openid缓存", openidStor)
      that.globalData.openid = openidStor;
    }
  },
  saveUserInfo(user) {
    wx.setStorageSync('user', user)
  },
  async getuserInfo(){
    console.log("openid",this.globalData.openid)
    const db=wx.cloud.database()
    await db.collection('all_user')
    .where({
      _openid:this.globalData.openid
    })
    .get()
    .then(res=>{
      console.log("用户信息",res.data)
      this.globalData.userInfo=res.data[0];
      console.log("app.globalData.userInfo",this.globalData.userInfo)
    })
  },
 
  updateAPPuserInfo()
  {
     db.collection('all_user')
     .where({
       _openid:app.globalData.openid
     })
     .get()
     .then(res=>{
       console.log("res",res.data[0])
       app.globalData.userInfo=res.data[0]
     })
  },
  async getTeamInfo(){
    const db=wx.cloud.database()
    await db.collection('all_team')
    .where({
      _openid:this.globalData.openid
    })
    .get()
    .then(res=>{
      console.log("团队信息",res.data)
      this.globalData.teamInfo=res.data[0]
      console.log("this.globalData.teamInfo",this.globalData.teamInfo)
    })
  },
   getTime(time)
   {  
    let curYear = new Date().getFullYear()
    let curMonth = new Date().getMonth() + 1
    let curDay = new Date().getDate()
    const timestamp = Date.parse(new Date());
    let d=new Date().toLocaleTimeString();
    let f=new Date().toString()
    let g=new Date().toTimeString()
    let t=f.slice(16,25)
    let r=f.slice(16,21)
    //0---返回日期格式 例如 2022-2-21
     if(time==0) return curYear+"-"+curMonth+"-"+curDay
     //1---返回日期格式 例如 2022年2月21日
     if(time==1) return curYear+"年"+curMonth+"月"+curDay+"日" 
     //2---返回当前日期的时间戳
     if(time==2) return timestamp
     //3---返回时间(精确到秒) 例如12.52.01
     if(time==3) return t
     //4--返回时间(精确到分)  例如12.51
     if(time==4)return r
     //5--返回时间+日期   例如2022-2-21 12.53
     if(time==5)return curYear+"-"+curMonth+"-"+curDay+" "+t
   },
   transferTime(time){
     var date=new Date(time)
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    var D = date.getDate() + ' ';
    var h = date.getHours() + ':';
    var m = date.getMinutes() ;
    return Y+M+D+h+m
   },
   getRandomCode(length) {
    if (length > 0) {
      var data = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
      var nums = "";
      for (var i = 0; i < length; i++) {
        var d = Math.random()
        var r = parseInt(Math.random() * 10);
        nums += data[r];
      }
      return nums;
    } else {
      return false;
    }
  },
  //返回ID长度为length+timestamp
  //例如getID(4,2)
  getID(length,timestamp) {
    var time = new Date().getTime()
    var timeString = time.toString()
    var timeRandom = timeString.substr(timeString.length - timestamp)
    return (timeRandom + this.getRandomCode(length));
  },
  editTabbar: function() {
    console.log("隐藏tabBar")
    let tabbar = this.globalData.tabBar;
    let currentPages = getCurrentPages();
    let _this = currentPages[currentPages.length - 1];
    let pagePath = _this.route;
    (pagePath.indexOf('/') != 0) && (pagePath = '/' + pagePath);
    for (let i in tabbar.list) {
      tabbar.list[i].selected = false;
      (tabbar.list[i].pagePath == pagePath) && (tabbar.list[i].selected = true);
    }
    _this.setData({
      tabbar: tabbar
    });
  },
  //自己对wx.hideTabBar的一个封装
hidetabbar() {
  wx.hideTabBar({
    fail: function() {
    // 做了个延时重试一次，作为保底。
        wx.hideTabBar()
    }
  });
},
getSystemInfo: function() {
  let t = this;
  wx.getSystemInfo({
    success: function(res) {
      t.globalData.systemInfo = res;
    }
  });
},
checkIsSign(a,signUrl){
   if(Object.keys(a).length==0)
   {
    wx.showModal({
      title: '先注册为志愿者才能使用',
      cancelText: '再看看',
      confirmText: '立刻注册',
success (res) {
if (res.confirm) {
console.log('用户点击确定')
wx.navigateTo({
  url: signUrl,
})
}else if (res.cancel) {
  console.log('用户点击取消')
  }
  }
    })
    return false
   }
   else
   {
     console.log("用户已经注册，无需弹窗") 
     return true
   }
},
  onLaunch:async function () {
    
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力');
    } else {
      wx.cloud.init({
        env: 'cloud1-5g9np9s88a72a0bc',
        traceUser: true,
      });
      }
    this.getSystemInfo()
    await this.getOpenid() 
    await this.getuserInfo()
    await this.getTeamInfo()
    console.log(this.getTime(4))
    console.log(this.transferTime(this.getTime(2)))
    setTimeout(() => {
       if(this.globalData.userInfo.userInfo.ID == undefined)
       {
        console.log("未注册,不跳转")
       }
       else{
        console.log("this.globalData.userInfo",this.globalData.userInfo)
        setTimeout(() => {
          console.log("跳转成功")
           wx.switchTab({
             url: '../home/home',
           })
        }, 1000);
      }
      if(Object.keys(this.globalData.teamInfo).length!=0){
        console.log("跳转到团队页");
        wx.reLaunch({
          url: '../team_all/team/team',
          success: (res) => {console.log('跳转到团队页成功',res)},
          fail: (res) => {console.log('跳转到团队页失败',res)},
          complete: (res) => {console.log('跳转到团队页失败',res)},
        })
      }
    }, 2500);
   
   0}
 
})


